package astoliarskyi.wicket;

import astoliarskyi.wicket.card.Card;
import java.util.EnumMap;

public class AttemptLogger {

	private DataByType dataByType;
	private TotalData totalWithoutCard;

	public AttemptLogger() {
		dataByType = new DataByType();
		totalWithoutCard = new TotalData();
	}

	void logAttempt(Card card, boolean decision) {
		Card.CardType cardType = null;
		if (card != null) {
			cardType = card.getCardType();
			if (decision) {
				dataByType.incAccepted(cardType);
			} else {
				dataByType.incRejected(cardType);
			}
		} else {
			if (decision) {
				totalWithoutCard.incAccepted();
			} else {
				totalWithoutCard.incRejected();
			}
		}

	}

	public TotalData getTotalStatistics() {
		TotalData total = new TotalData();
		for (Card.CardType cardType : Card.CardType.values()) {
			TotalData totalForCardType = dataByType.getTotalDataByType(cardType);
			total.setTotalAccepted(total.getTotalAccepted() + totalForCardType.getTotalAccepted());
			total.setTotalRejected(total.getTotalRejected() + totalForCardType.getTotalRejected());
		}
		total.setTotalAccepted(total.getTotalAccepted() + totalWithoutCard.getTotalAccepted());
		total.setTotalRejected(total.getTotalRejected() + totalWithoutCard.totalRejected);
		return total;
	}

	public DataByType getTotalStatisticsByCardType() {
		return dataByType;
	}

	public static class TotalData {

		private int totalAccepted;
		private int totalRejected;

		public synchronized int getTotalAccepted() {
			return totalAccepted;
		}

		public synchronized void setTotalAccepted(int totalAccepted) {
			this.totalAccepted = totalAccepted;
		}

		public synchronized void incAccepted() {
			totalAccepted = totalAccepted + 1;
		}

		public synchronized void incRejected() {
			totalRejected = totalRejected + 1;
		}

		public synchronized int getTotalRejected() {
			return totalRejected;
		}

		public synchronized void setTotalRejected(int totalRejected) {
			this.totalRejected = totalRejected;
		}
	}

	public static class DataByType {

		private EnumMap<Card.CardType, TotalData> totalDataByType
				= new EnumMap<Card.CardType, TotalData>(Card.CardType.class);

		public DataByType() {
			for (Card.CardType cardType : Card.CardType.values()) {
				totalDataByType.put(cardType, new TotalData());
			}
		}

		public void incAccepted(Card.CardType cardType) {
			totalDataByType.get(cardType).incAccepted();
		}

		public void incRejected(Card.CardType cardType) {
			totalDataByType.get(cardType).incRejected();
		}

		public TotalData getTotalDataByType(Card.CardType cardType) {
			return totalDataByType.get(cardType);
		}
	}
}
